package com.wnhz.work.yz.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PtrRecyclerView;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.wnhz.work.yz.BaseActivity;
import com.wnhz.work.yz.MyApplication;
import com.wnhz.work.yz.R;
import com.wnhz.work.yz.base.BaseRVAdapter;
import com.wnhz.work.yz.base.BaseViewHolder;
import com.wnhz.work.yz.bean.IndustContentBean;
import com.wnhz.work.yz.bean.IndustryTitleBean;
import com.wnhz.work.yz.utils.Url;
import com.wnhz.work.yz.utils.xutils3.MyCallBack;
import com.wnhz.work.yz.utils.xutils3.XUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * ---工业化内装
 */
public class IndustryFitmentActivity extends BaseActivity implements View.OnClickListener {

    private RecyclerView title_recycler;
    private PtrRecyclerView content_recycler;
    private ImageView unfold;
    private BaseRVAdapter<List<IndustryTitleBean.InfoEntity>> adapter5;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_industry_fitment);
        initTilte();
        initView();
        initData();

    }

    private int cateid = -1, orderid = -1, areaid = -1;

    private void initView() {
        title_recycler = (RecyclerView) findViewById(R.id.title_recycler);
        content_recycler = (PtrRecyclerView) findViewById(R.id.content_recycler);
        content_recycler.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
    }

    private void initData() {
        showDialog();
        upload();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //返回后退出更新浏览量
        // upload2Content();
    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    private List<IndustryTitleBean.InfoEntity> info = new ArrayList<>();

    private void upload() {
        Map<String, Object> map = new HashMap<>();
        XUtil.Post(Url.BATH_CATELIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Gson gson = new Gson();
                Log.e("=-==", result);
                info.clear();
                IndustryTitleBean bean = gson.fromJson(result, IndustryTitleBean.class);
                info = bean.getInfo();
                for (int j = 0; j < info.size(); j++) {
                    IndustryTitleBean.InfoEntity.CateEntity c = new IndustryTitleBean.InfoEntity.CateEntity();
                    c.setCateid("-1");
                    c.setCatename("全部");
                    info.get(j).getCate().add(0, c);
                }
                Log.e("---", info.toString());
            }

            @Override
            public void onFinished() {
                super.onFinished();
                setAllTitle();
                upload2Content();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private AlertDialog.Builder builder;
    private AlertDialog show;

    private void setAllTitle() {
        title_recycler.setLayoutManager(new GridLayoutManager(IndustryFitmentActivity.this, info.size(), LinearLayoutManager.VERTICAL, false));
        adapter5 = new BaseRVAdapter(IndustryFitmentActivity.this, info) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.industry_item_title;
            }

            @Override
            public void onBind(final BaseViewHolder holder, final int position) {
                holder.setTextView(R.id.tv_item_title, info.get(position).getName());
                final List<IndustryTitleBean.InfoEntity.CateEntity> cate = info.get(position).getCate();

                holder.getTextView(R.id.tv_item_title).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {


                        //  Drawable drawable = getResources().getDrawable(R.mipmap.list_pull_down_iocn);
                        //  drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
                        //  holder.getTextView(R.id.tv_item_title).setCompoundDrawables(null, null, drawable, null);
                        Intent intent = new Intent(IndustryFitmentActivity.this, DialogIndustryActivity.class);
                        intent.putExtra("position", position);
                        ArrayList<IndustryTitleBean.InfoEntity> info2 = (ArrayList<IndustryTitleBean.InfoEntity>) info;
                        intent.putExtra("info", info2);
                        ArrayList<IndustryTitleBean.InfoEntity.CateEntity> cate2 = (ArrayList<IndustryTitleBean.InfoEntity.CateEntity>) cate;
                        intent.putExtra("cate", cate2);
                        intent.putExtra("cateid", cateid);
                        intent.putExtra("orderid", orderid);
                        intent.putExtra("areaid", areaid);


                        startActivityForResult(intent, 123);


                        //----
                       /* builder = new AlertDialog.Builder(IndustryFitmentActivity.this);
                        View view = View.inflate(IndustryFitmentActivity.this, R.layout.dialog_industry_sort, null);
                        final RecyclerView min_title_select = (RecyclerView) view.findViewById(R.id.min_title_select);
                        min_title_select.setLayoutManager(new LinearLayoutManager(IndustryFitmentActivity.this, LinearLayoutManager.VERTICAL, false));
                        ((TextView) view.findViewById(R.id.title_text)).setText(info.get(position).getName());
                        min_title_select.addItemDecoration(new RecycleViewDivider(IndustryFitmentActivity.this, RecyclerView.HORIZONTAL));


                        builder.setView(view);
                        if (show != null) {
                            show.dismiss();
                        }
                        show = builder.show();
                        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                show.dismiss();
                            }
                        });
                        Window dialogWindow = show.getWindow();
                        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
                        dialogWindow.setGravity(Gravity.RIGHT | Gravity.BOTTOM);
                        lp.width = getWindowManager().getDefaultDisplay().getWidth() / 3 * 2;
                        lp.height = getWindowManager().getDefaultDisplay().getHeight() / 7 * 6;

                        dialogWindow.setAttributes(lp);
                        dialogWindow.setWindowAnimations(R.style.dialogWindowAnim2); //设置窗口弹出动画


                        min_title_select.setAdapter(new BaseRVAdapter(IndustryFitmentActivity.this, cate) {
                            @Override
                            public int getLayoutId(int viewType) {
                                return R.layout.item_min_title_select;
                            }

                            @Override
                            public void onBind(BaseViewHolder holder2, final int position2) {
                                final TextView select = holder2.getTextView(R.id.item_min_select_text);

                                switch (position) {
                                    case 0:
//                                        Log.e("---" + cate.get(position).getCateid() + "---", "" + cateid);
                                        if (cate.get(position2).getCateid().equals(cateid + "")) {
                                            select.setTextColor(getResources().getColor(R.color.main_color));
                                        } else {
                                            select.setTextColor(getResources().getColor(R.color.text));
                                        }
                                        break;
                                    case 1:
                                        if (cate.get(position2).getCateid().equals(orderid + "")) {
                                            select.setTextColor(getResources().getColor(R.color.main_color));
                                        } else {
                                            select.setTextColor(getResources().getColor(R.color.text));
                                        }
                                        break;
                                    case 2:
                                        if (cate.get(position2).getCateid().equals(areaid + "")) {
                                            select.setTextColor(getResources().getColor(R.color.main_color));
                                        } else {
                                            select.setTextColor(getResources().getColor(R.color.text));
                                        }
                                        break;
                                }

                                holder2.setTextView(R.id.item_min_select_text, cate.get(position2).getCatename());
                                select.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {

                                        show.dismiss();
                                        //根据你点击的第几个，然后判断
                                        switch (position) {
                                            case 0:
                                                cateid = Integer.parseInt(info.get(position).getCate().get(position2).getCateid());
                                                break;
                                            case 1:
                                                orderid = Integer.parseInt(info.get(position).getCate().get(position2).getCateid());
                                                break;
                                            case 2:
                                                areaid = Integer.parseInt(info.get(position).getCate().get(position2).getCateid());
                                                break;
                                        }
                                        //设置选择哪个换字上去
//                                        info.get(position).setName(info.get(position).getCate().get(position2).getCatename());
//                                        adapter5.notifyDataSetChanged();
                                        upload2Content();
//                                        Drawable drawable = getResources().getDrawable(R.mipmap.list_pulldown_iocn3x_right);
//                                        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
//                                        holder.getTextView(R.id.tv_item_title).setCompoundDrawables(null, null, drawable, null);
                                    }
                                });
                            }

                        });*/


                    }


                });
            }

        };
        title_recycler.setAdapter(adapter5);

    }

    List<IndustContentBean.InfoEntity> indust_info = new ArrayList<>();
    List<IndustContentBean.InfoEntity> indust_info2 = new ArrayList<>();

    private void setAllContent(int type) {
        //   Log.e("", "---" + indust_info2.size() + "----" + indust_info.size());
        //  Log.e("", "---type:" + type);
        if (type == 1) {
            adapter = new MyAdapter(this, indust_info2);
            content_recycler.setAdapter(adapter);
        } else {
            if (indust_info2.size() >= 1)
                //    Log.e("---", indust_info2.get(0).getIndex_pic());
                adapter1 = new MyAdapter1(this, indust_info2);
            content_recycler.setAdapter(adapter1);
        }
        content_recycler.setMode(PullToRefreshBase.Mode.BOTH);
        content_recycler.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<RecyclerView>() {
            @Override
            public void onPullDownToRefresh(final PullToRefreshBase<RecyclerView> refreshView) {
                // showDialog();
                page0 = 0;
                upload2Content();
                refreshView.onRefreshComplete();
            }

            @Override
            public void onPullUpToRefresh(final PullToRefreshBase<RecyclerView> refreshView) {
                refreshView.onRefreshComplete();
                page0++;
                a:
                for (int i = 0; i < nums; i++) {
                    //  Log.e("---", indust_info.size() + "--" + indust_info2.size());
                    if (indust_info2.size() < indust_info.size()) {
                        indust_info2.add(indust_info.get(i + nums * page0));
                        if (adapter1 != null)
                            adapter1.notifyItemInserted(indust_info2.size() - 1);
                        if (adapter != null)
                            adapter.notifyItemInserted(indust_info2.size() - 1);
                    } else {
                     //   MyToast("没有更多了");
                        break a;
                    }
                }
            }
        });
    }

    private int nums = 6;
    private int page0 = 0;
    private MyAdapter adapter;
    private MyAdapter1 adapter1;

    class MyAdapter extends BaseRVAdapter {

        /**
         * 构造器
         *
         * @param context 上下文
         * @param list    数据集合
         */
        public MyAdapter(Context context, @NonNull List list) {
            super(context, list);
        }

        @Override
        public int getLayoutId(int viewType) {
            return R.layout.industry_item_content;
        }

        @Override
        public void onBind(final BaseViewHolder holder, final int position) {
           // x.image().bind(holder.getImageView(R.id.img), indust_info2.get(position).getIndex_pic());


            ImageLoader.getInstance().displayImage(indust_info2.get(position).getIndex_pic(),holder.getImageView(R.id.img));
            // ImageLoadUrl.downloadImgByUrl(indust_info2.get(position).getIndex_pic(),100*100,holder.getImageView(R.id.img));
            holder.getView(R.id.img).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(IndustryFitmentActivity.this, IndustryDetialsActivity.class);
                    intent.putExtra("goodsId", indust_info2.get(position).getGoods_id());
                    startActivity(intent);
                }
            });
            holder.setTextView(R.id.content_title, indust_info.get(position).getGoods_name());
            holder.setTextView(R.id.like, indust_info.get(position).getPraise_nums());
            holder.setTextView(R.id.love, indust_info.get(position).getCollect_nums());
            holder.setTextView(R.id.look, indust_info.get(position).getClick_nums() + "人浏览");
            //是否点赞
            if ("1".equals(indust_info.get(position).getIs_praise())) {
                Drawable drawable = getResources().getDrawable(R.mipmap.dianzan_li2);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
                holder.getTextView(R.id.like).setCompoundDrawables(drawable, null, null, null);
            } else {
                Drawable drawable = getResources().getDrawable(R.mipmap.home_like_icon);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
                holder.getTextView(R.id.like).setCompoundDrawables(drawable, null, null, null);
            }
            //是否收藏
            if ("1".equals(indust_info.get(position).getIs_collect())) {
                Drawable drawable = getResources().getDrawable(R.mipmap.home_love_icon);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
                holder.getTextView(R.id.love).setCompoundDrawables(drawable, null, null, null);
            } else {
                Drawable drawable = getResources().getDrawable(R.mipmap.aixin_nor);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight()); //设置边界
                holder.getTextView(R.id.love).setCompoundDrawables(drawable, null, null, null);
            }

            //收藏
            holder.getTextView(R.id.love).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    upLoadCollect(indust_info2.get(position).getGoods_id(), position);
                }
            });
            //点赞
            holder.getTextView(R.id.like).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    upLoadPraise(indust_info2.get(position).getGoods_id(), position);
                }
            });


        }


    }


    // 点赞
    private void upLoadPraise(String goods_id, final int position) {
        Map<String, Object> map = new HashMap<>();
        map.put("goodsId", goods_id);
        if (MyApplication.getInstance().getUserBean() == null) {
            startActivity(new Intent(getApplicationContext(), LoginFirstActivity.class));
            return;
        } else {
            map.put("token", MyApplication.getInstance().getUserBean().getToken());
        }
        XUtil.Post(Url.BATH_ISPRAISE, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("----", result + "");
                super.onSuccess(result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    MyToast(info);
                    if (res.equals("1")) {
                        if (info.contains("取消")) {
                            indust_info2.get(position).setIs_praise("0");
                            indust_info2.get(position).setPraise_nums(Integer.parseInt(indust_info2.get(position).getPraise_nums()) - 1 + "");
                        } else {
                            indust_info2.get(position).setIs_praise("1");
                            indust_info2.get(position).setPraise_nums(Integer.parseInt(indust_info2.get(position).getPraise_nums()) + 1 + "");
                        }
                    }
                    adapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    //收藏
    private void upLoadCollect(String goods_id, final int position) {
        Map<String, Object> map = new HashMap<>();
        map.put("goodsId", goods_id);
        if (MyApplication.getInstance().getUserBean() == null) {
            startActivity(new Intent(getApplicationContext(), LoginFirstActivity.class));
            return;
        } else {
            map.put("token", MyApplication.getInstance().getUserBean().getToken());
        }
        XUtil.Post(Url.BATH_ISCOLLECT, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e("----", result + "");
                super.onSuccess(result);
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("result");
                    String info = jsonObject.optString("info");
                    MyToast(info);
                    if (res.equals("1")) {
                        if (info.contains("取消")) {
                            indust_info2.get(position).setIs_collect("0");
                            indust_info2.get(position).setCollect_nums(Integer.parseInt(indust_info2.get(position).getCollect_nums()) - 1 + "");
                        } else {
                            indust_info2.get(position).setIs_collect("1");
                            indust_info2.get(position).setCollect_nums(Integer.parseInt(indust_info2.get(position).getCollect_nums()) + 1 + "");
                        }
                    }
                    adapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }


    class MyAdapter1 extends BaseRVAdapter {

        /**
         * 构造器
         *
         * @param context 上下文
         * @param list    数据集合
         */
        public MyAdapter1(Context context, @NonNull List list) {
            super(context, list);
        }

        @Override
        public int getLayoutId(int viewType) {
            return R.layout.industry_item_content2;
        }

        @Override
        public void onBind(BaseViewHolder holder, final int position) {
//            x.image().bind(holder.getImageView(R.id.img), indust_info2.get(position).getIndex_pic());

            ImageLoader.getInstance().displayImage(indust_info2.get(position).getIndex_pic(),holder.getImageView(R.id.img));

            // ImageLoadUrl.downloadImgByUrl(indust_info2.get(position).getIndex_pic(),100*100,holder.getImageView(R.id.img));

            ViewGroup.LayoutParams lp = holder.getImageView(R.id.img).getLayoutParams();
            switch (position % 2) {
                case 0:
                    lp.height = MyApplication.getInstance().window_h / 2-70;
                    break;
                case 1:
                    lp.height = MyApplication.getInstance().window_h / 3 -20;
                    break;
            }
            holder.getImageView(R.id.img).setLayoutParams(lp);
            holder.getView(R.id.ll_max).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(IndustryFitmentActivity.this, IndustryDetialsActivity.class);
                    intent.putExtra("goodsId", indust_info2.get(position).getGoods_id());
                    startActivity(intent);
                }
            });

        }


    }

    private void upload2Content() {
        // 列表 参数 token(选填) orderid(排序id)、cateid(风格id)、areaid(面积id)
        //#define k_bath_modelList @"bath_modelList"

        Map<String, Object> map = new HashMap<>();
        if (orderid != -1)
            map.put("orderid", orderid);
        if (cateid != -1)
            map.put("cateid", cateid);
        if (areaid != -1)
            map.put("areaid", areaid);
        if (MyApplication.getInstance().getUserBean() != null)
            map.put("token", MyApplication.getInstance().getUserBean().getToken());
        Set keys = map.keySet();
        if (keys != null) {
            Iterator iterator = keys.iterator();
            while (iterator.hasNext()) {
                Object key = iterator.next();
                Object value = map.get(key);
                Log.e("" + key, ":" + value + "\n");
            }
        }

        // Log.e("---", cateid + "--" + orderid + "---" + areaid);
        XUtil.Post(Url.BATH_MODELLIST, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.e("--", result + "");
                indust_info.clear();
                indust_info2.clear();
                page0 = 0;
                IndustContentBean bean = new Gson().fromJson(result, IndustContentBean.class);
                indust_info = bean.getInfo();
                //   Log.e("----", indust_info.size() + "");
            }

            @Override
            public void onFinished() {
                super.onFinished();
                //setAllTitle();
                closeDialog();
                a:
                for (int i = 0; i < nums; i++) {
                    //Log.e("---", indust_info.size() + "--" + indust_info2.size());
                    if (indust_info2.size() < indust_info.size()) {
                        indust_info2.add(indust_info.get(i + nums * page0));
                        if (adapter1 != null)
                            adapter1.notifyItemInserted(indust_info2.size() - 1);
                        if (adapter != null)
                            adapter.notifyItemInserted(indust_info2.size() - 1);
                    } else {
                    //    MyToast("没有更多了");
                        break a;
                    }
                }
                content_recycler.setLayoutManager(isGridLayout ? new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) : new LinearLayoutManager(IndustryFitmentActivity.this, LinearLayoutManager.VERTICAL, false));
                if (!isGridLayout) {
                    setAllContent(1);
                } else {
                    setAllContent(2);
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                closeDialog();
                super.onError(ex, isOnCallback);
            }
        });
    }

    private void initTilte() {
        TextView title = (TextView) findViewById(R.id.view_main_middle_title);
        title.setText("工业化内装");
        findViewById(R.id.btn_main_left).setOnClickListener(this);
        unfold = (ImageView) findViewById(R.id.unfold2);
        unfold.setOnClickListener(this);
        unfold.setVisibility(View.VISIBLE);
        findViewById(R.id.tv_right).setVisibility(View.GONE);
    }

    private boolean isGridLayout = false;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_main_left:
                finish();
                break;
            case R.id.unfold2:
                isGridLayout = !isGridLayout;
                content_recycler.setLayoutManager(isGridLayout ? new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) : new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
                unfold.setImageResource(isGridLayout ? R.mipmap.nav_merge_view_iconx : R.mipmap.nav_unfold_view_iconx);
                if (!isGridLayout) {
                    setAllContent(1);
                } else {
                    setAllContent(2);
                }
                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 123:
                if (resultCode == RESULT_OK) {
                    if (data != null) {
                        cateid = data.getIntExtra("cateid", -1);
                        orderid = data.getIntExtra("orderid", -1);
                        areaid = data.getIntExtra("areaid", -1);
                        showDialog();
                        upload2Content();
                    }
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}
